class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next = None

class List(object):
    def __init__(self):
        self.head = Node()
        self.length = 0

    def insert(self, pos, data):
        assert pos >= 0 and pos <= self.length

# Find out the position to insert.
        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

# Insert new node
        newNode = Node()
        newNode.data = data
        newNode.next = tmpPtr.next
        tmpPtr.next = newNode
        self.length += 1
        

    def append(self, data):
        self.insert(self.length, data)

    def remove(self, pos):
        assert pos < self.length
        
        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        if tmpPtr.next is not None:
           delNode = tmpPtr.next
           tmpPtr.next = delNode.next
           self.length -= 1

    def foreach(self):
        tmpPtr = self.head.next
        while tmpPtr is not None:
            yield tmpPtr.data
            tmpPtr = tmpPtr.next

if __name__ == "__main__":
     l = List()
     l.append(1)
     l.append(2)
     l.append(3)
     l.append(4)
     l.append(5)

     for x in l.foreach():
         print(x)

     print("Insert new data 7")
     l.insert(1, 7)
     for x in l.foreach():
         print(x)

     print("Remove the 2th element")
     l.remove(1)
     for x in l.foreach():
         print(x)

